package com.cwx.web.admin;

import com.cwx.pojo.Tag;
import com.cwx.pojo.Type;
import com.cwx.service.TagsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagsService tagsService;

    //标签首页列表
    @GetMapping("/tags")
    public String type(@PageableDefault(size = 3,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable, Model model){
        Page<Tag> tags = tagsService.listTag(pageable);
        model.addAttribute("page",tags);
        return "admin/tags";
    }

    //页面跳转
    @GetMapping("/tinput")
    public String input(Model model){
        model.addAttribute("tag",new Tag());
        return "admin/tags-input";
    }


    //添加一个新的标签
    @PostMapping("/addTags")
    public String addTypes(Tag tag, RedirectAttributes attributes){
        Tag tag1 = tagsService.saveTag(tag);
        if (tag1 != null){
            attributes.addFlashAttribute("message","添加标签成功");
        }
        return "redirect:/admin/tags";
    }

    //前端AJAX请求
    @GetMapping("/tname")
    @ResponseBody
    public String name(String name){
        Tag tag = tagsService.getTag(name);
        if (tag== null){
            return "true";
        }else {
            return "false";
        }
    }


    //编辑用户请求
    @PostMapping("/addtags/{id}")
    public String editorType(@PathVariable Long id, Tag tag){
        tagsService.updateTag(id,tag);
        return "redirect:/admin/tags";
    }

    //删除一个用户
    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id){
        tagsService.deleteTag(id);
        return "redirect:/admin/tags";
    }

}
